package karaoke.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import karaoke.excepcion.DAOExcepcion;
import karaoke.modelo.Cliente;
import karaoke.modelo.Local;
import karaoke.modelo.Reserva;
import karaoke.negocio.GestionClientes;
import karaoke.negocio.GestionLocales;
import karaoke.negocio.GestionReserva;

/**
 * Servlet implementation class LoginUsuarioServlet
 */
@WebServlet("/LoginUsuarioServlet")
public class LoginUsuarioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginUsuarioServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String email = request.getParameter("txtemail");
		String password = request.getParameter("txtpassword");
		
		GestionClientes negocioCliente = new GestionClientes();
		ArrayList<String> errors = new ArrayList<String>();
		RequestDispatcher rd = null;
		
		try {
			Cliente c = negocioCliente.obtener(email, password);
			
			if(c.getNombres()!=null){
				HttpSession sesion = request.getSession();
				sesion.setAttribute("CLIENTE", c);
				//cargarDataReservaCliente(c, request);
				rd = request.getRequestDispatcher("/reservas.jsp");
			} else {
				errors.add("Ingreso Invalido");
				rd = request.getRequestDispatcher("/login-register-user.jsp");
			}
			
			
			
		} catch (DAOExcepcion e) {
			errors.add("Fallo el ingreso");
		}
		
		request.setAttribute("ERRORS", errors);
		rd.forward(request, response);
	}

	protected void cargarDataReservaCliente(Cliente c, HttpServletRequest request) throws DAOExcepcion{
		GestionLocales negocioL = new GestionLocales();
		Collection<Local> locales = negocioL.listar();
		
		request.setAttribute("LOCALES", locales);
		
		GestionReserva negocioR = new GestionReserva();
		Collection<Reserva> reservasCli = negocioR.listByCodNomSalaReservaByIdCliente(c.getIdcliente(), "", "");
		
		request.setAttribute("RESERVAS", reservasCli);
	}
}
